package com.hardware.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hardware.common.R;
import com.hardware.dto.EmployeeDto;
import com.hardware.entity.Employee;
import com.hardware.entity.system.Module;
import com.hardware.entity.system.Navigation;
import com.hardware.entity.system.RoleModule;
import com.hardware.entity.system.RoleUser;
import com.hardware.service.EmployeeService;
import com.hardware.service.system.ModuleService;
import com.hardware.service.system.RoleModuleService;
import com.hardware.service.system.RoleUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.hardware.utils.RedisConstants.CACHE_EMPLOYEE_KEY;

/**
 * 人员管理：部门人员
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleUserService roleUserService;



    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<EmployeeDto> login(HttpServletRequest request, @RequestBody Employee employee){
        return employeeService.login(request,employee);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    @CacheEvict(value = CACHE_EMPLOYEE_KEY,allEntries = true)
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){

        return employeeService.save(request,employee);
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = CACHE_EMPLOYEE_KEY,key = "#page +'_'+ #pageSize")
    public R<Page> page(int page, int pageSize, String name){
        return employeeService.page(page,pageSize,name);

    }

    /**
     * 根据id修改员工信息
     * @param employee
     * @return
     */
    @PutMapping
    @CacheEvict(value = CACHE_EMPLOYEE_KEY,allEntries = true)
    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
//        log.info(employee.toString());
        return employeeService.update(request,employee);
    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = CACHE_EMPLOYEE_KEY,key = "#id")
    public R<EmployeeDto> getById(@PathVariable Long id){
//        log.info("根据id查询员工信息...");
        Employee employee = employeeService.getById(id);
        EmployeeDto employeeDto = new EmployeeDto();
        BeanUtil.copyProperties(employee,employeeDto);
        LambdaQueryWrapper<RoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleUser::getUserId,id);

        RoleUser one = roleUserService.getOne(queryWrapper);
        employeeDto.setAuthorId(one.getRoleId());
        if(employeeDto != null){
            return R.success(employeeDto);
        }
        return R.error("没有查询到对应员工信息");
    }

    /**
     * 更新权限
     * @param
     * @return
     */
    @PostMapping("/author")
    public R<String> author(@RequestBody EmployeeDto employeeDto){
        LambdaQueryWrapper<RoleUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleUser::getUserId,employeeDto.getId());
        roleUserService.remove(queryWrapper);
        RoleUser roleUser = new RoleUser();
        roleUser.setRoleId(employeeDto.getAuthorId());
        roleUser.setUserId(employeeDto.getId());
        roleUserService.save(roleUser);

        return R.success("更新成功");
    }
    @Autowired
    private RoleModuleService roleModuleService;
    @Autowired
    private ModuleService moduleService;
    @GetMapping("/menu/{id}")
    public R<List<Navigation>> menu(@PathVariable Long id){
        //用户ID 查询role ID
        LambdaQueryWrapper<RoleUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoleUser::getUserId,id);
        RoleUser roleUser = roleUserService.getOne(lambdaQueryWrapper);
        //roleId 查 moduleId
        LambdaQueryWrapper<RoleModule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoleModule::getRoleId,roleUser.getRoleId());
        List<RoleModule> modules = roleModuleService.list(queryWrapper);
        //moduleId 查询出对应权限
        List<Navigation> navigations = new ArrayList<>();
        //封装导航
        for (RoleModule item : modules) {
            Module module = moduleService.getById(item.getModuleId());
                Navigation navigation = new Navigation();
                navigation.setId(module.getId());
                navigation.setUrl(module.getCurl());
                navigation.setName(module.getName());

                LambdaQueryWrapper<Module> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Module::getParentId,module.getId());
                List<Module> list = moduleService.list(queryWrapper1);

                if(list.size() > 0){
                    List<Navigation> collect1 = new ArrayList<>();
                    for (Module item1 : list) {
                        LambdaQueryWrapper<RoleModule> queryWrapper2 = new LambdaQueryWrapper<>();
                        queryWrapper2.eq(RoleModule::getRoleId,roleUser.getRoleId()).eq(RoleModule::getModuleId,item1.getId());
                        RoleModule one = roleModuleService.getOne(queryWrapper2);
                        if(one != null){
                            Navigation navigation2 = new Navigation();
                            navigation2.setId(item1.getId());
                            navigation2.setName(item1.getName());
                            navigation2.setUrl(item1.getCurl());
                            collect1.add(navigation2);
                        }
                    }
                    /*List<Navigation> collect1 = list.stream().map((item1) -> {
                        LambdaQueryWrapper<RoleModule> queryWrapper2 = new LambdaQueryWrapper<>();
                        queryWrapper2.eq(RoleModule::getRoleId,roleUser.getRoleId()).eq(RoleModule::getModuleId,item1.getId());
                        RoleModule one = roleModuleService.getOne(queryWrapper2);
                        if(one != null){
                            Navigation navigation2 = new Navigation();
                            navigation2.setId(item1.getId());
                            navigation2.setName(item1.getName());
                            navigation2.setUrl(item1.getCurl());
                            return navigation2;
                        }

                    }).collect(Collectors.toList());*/
                    navigation.setChildren(collect1);
                }

                if(navigation.getChildren() != null)
                    navigations.add(navigation);
        }
        //封装成 navigation
        return R.success(navigations);
    }

}
